#层次聚类实例

import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import AgglomerativeClustering
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.datasets import make_blobs
# 示例数据
np.random.seed(123)
X, y = make_blobs(centers=4, n_samples=1000)#生成4个随机簇
print('数据的维数:', X.shape)
print('数据的簇标签：', y)

clustering = AgglomerativeClustering(n_clusters=4)
labels = clustering.fit_predict(X)
# 可视化结果
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', marker='o', edgecolor='k', s=50)
plt.title('Hierarchical Clustering')

# 计算链接矩阵
linked = linkage(X, 'ward')

# 绘制树状图
plt.figure(figsize=(10, 7))
dendrogram(linked, orientation='top', labels=labels, distance_sort='descending', show_leaf_counts=True)
plt.title('Hierarchical Clustering Dendrogram')
plt.show()